package com.panda.admin.login.access.controller;

import cn.hutool.captcha.*;
import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.panda.admin.login.dto.LoginDto;
import com.panda.admin.login.dto.PasswordDto;
import com.panda.admin.login.dto.RegisterDto;
import com.panda.admin.login.entity.SystemUser;
import com.panda.admin.login.auth.service.SystemUserService;
import com.panda.admin.result.Result;
import com.panda.admin.result.ResultEnums;
import com.panda.admin.result.ServiceException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * author: tcy
 * createDate: 2023/6/13
 * description:注册控制
 */
@Api(tags = "注册控制")
@RestController
@RequestMapping("/enroll")
public class SystemRegisterController {

    @Autowired
    SystemUserService systemUserService;

    @ApiOperation(value = "系统注册")
    @PostMapping("/register")
    public Result<SystemUser> register(@RequestBody RegisterDto dto){
        return Result.success(systemUserService.register(dto));
    }

    @ApiOperation(value = "秘文密码")
    @GetMapping("/passWord/{word}")
    public Result<String> password(@PathVariable String word){
        String encode = systemUserService.encryption(word);
        return Result.success(encode);
    }

    @ApiOperation(value = "验证码")
    @GetMapping("/captcha/{uuid}")
    public void captcha(HttpServletResponse response, @PathVariable("uuid") String uuid) throws IOException {
        /**
         * 圆形：CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(135,35,5,20);
         * 扭曲：ShearCaptcha shearCaptcha = CaptchaUtil.createShearCaptcha(135,35,5,20);
         * 动图：GifCaptcha gifCaptcha = CaptchaUtil.createGifCaptcha(135,35,5);
         */
        // 定义图形验证码的长、宽、验证码字符数、干扰元素个数
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(135, 34, 5, 10);
        // getCode()获取验证码
        String captchaCode = lineCaptcha.getCode();
        if (ObjectUtil.isNotEmpty(captchaCode)){
            systemUserService.mathSaveCaptcha(captchaCode,uuid);
        }else {
            throw new ServiceException("验证码刷新失败");
        }
        // 图形验证码写出，可以写出到文件，也可以写出到流
        lineCaptcha.write(response.getOutputStream());
        // 关闭流
        response.getOutputStream().close();
    }

    @ApiOperation(value = "运算验证码")
    @GetMapping("/mathCaptcha/{uuid}")
    public void mathCaptcha(HttpServletResponse response,@PathVariable("uuid") String uuid) throws IOException {
        // 这里定义的字符数无效，干扰元素有效
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(135, 34,1,10);
        // 自定义验证码内容为四则运算方式
        lineCaptcha.setGenerator(new MathGenerator());
        // 重新生成code
        lineCaptcha.createCode();
        // getCode()获取验证码
        String captchaCode = lineCaptcha.getCode();
        if (ObjectUtil.isNotEmpty(captchaCode)){
            systemUserService.mathSaveCaptcha(captchaCode,uuid);
        }else {
            throw new ServiceException("验证码刷新失败");
        }
        // 图形验证码写出
        lineCaptcha.write(response.getOutputStream());
        // 关闭流
        response.getOutputStream().close();
    }


    @ApiOperation(value = "后台登录")
    @PostMapping("/manageLogin")
    public Result<Object> manageLogin(@RequestBody LoginDto loginDto){
        try {
            return Result.success(systemUserService.manageLogin(loginDto));
        }catch (Exception e){
            String message = e.getMessage();
            System.out.println("输出异常：" + message);
            if (ObjectUtil.isNotEmpty(message) && message.contains("{") && message.contains("}")) {
                String info = "{" + StrUtil.subBetween(message, "{", "}") +"}";
                JSONObject jsonObject = JSONUtil.parseObj(info);
                if (ObjectUtil.isEmpty(jsonObject.getStr("data"))){
                    return Result.fail(ResultEnums.Fail.getMsg());
                }
                return Result.fail(jsonObject.getStr("data"));
            }
            if (message.contains("验证码")){
                return Result.fail(message);
            }
            return Result.fail("网络错误");
        }
    }

    @ApiOperation(value = "修改密码")
    @PostMapping("/updatePassword")
    public Result<String> updatePassword(@RequestBody PasswordDto passwordDto){
        return Result.success(systemUserService.updatePassword(passwordDto));
    }
}
